define(['ejs'],function(ejs){
	var module = {};
	//slice string to some length
	//longer than that will be replaced with '...'
	module.strSnip = function(str,len){
		len = len === undefined ? 10 : len;
		return (str.length > len ? str.slice(0,len)+'...' : str);
	};
	//format date into 2012-4-2 12:50 like String
	module.dateFormat = function(date,dateOnly){
		date = date === undefined ? new Date : date;
		if( dateOnly ){//近返回日期
			return [
			date.getFullYear(),
			date.getMonth()+1,
			date.getDate()
			].join('-');
		}else{//返回日期和时间
			return [
			date.getFullYear(),
			date.getMonth()+1,
			date.getDate()
			].join('-') +' '+ date.getHours() +':'+ date.getMinutes();
		}
	};
	//user accessor
	module.getUser = function(){
		return JSON.parse(module.readCookie('user'));
	};
	module.setUser = function(data){
		var user;
		//格式化用户生日字符串
		if( typeof(data) !== 'object' ){
			user = JSON.parse(data);
		}else{
			user = data.attributes || data;
		}
		var birthday = user.userInfo.birthday;
		if( birthday ){
			var parts = birthday.split('(');
			//是否已格式化
			if( parts.length === 2){
				user.userInfo.birthday = 
					module.dateFormat(
						new Date(parseInt(parts[1].split('+')[0])),
						true
					);
			}
		}
		data = JSON.stringify(user);
		module.createCookie('user',data);
	};
	//random number generator
	module.randomInt = function(start,end){
		//both undefined
		start = start === undefined ? 0 : start;
		end = end === undefined ? 10 : end;
		//only define end
		if( start !== undefined && end === undefined ){
			start = 0;
			end = start;
		} 
		return Math.round(Math.random()  * ( end - start ) + start);
	};

	//template render system from ejs
	module.ejs = require('ejs');
	module.ejs.open = '{%';
	module.ejs.close = '%}';
	
	//cookie manipulation
	//from www.quirkmode.org/js/cookies.html
	module.createCookie = function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	};

	module.readCookie = function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	};

	module.eraseCookie = function(name) {
		module.createCookie(name,"",-1);
	};

	return module;
});